package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.domain.TSmjGoodList;
import com.ruoyi.business.domain.TSmjMachineList;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.BasePayment;
import com.ruoyi.business.service.CommonService;
import com.ruoyi.business.service.ITSmjGoodListService;
import com.ruoyi.business.service.ITSmjMachineListService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.SignUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtil;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

@Service("smjmssmPayService")
public class SmjmsSmPayService extends BasePayment {

    @Resource
    public ITSmjMachineListService itSmjMachineListService;
    @Resource
    public ITSmjGoodListService itSmjGoodListService;
    @Resource
    private CommonService commonService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysConfigService sysConfigService;

    private TSmjGoodList getPayInfoObj(TRecipientInfo tUserRecipientInfo,TOrderInfo tOrderInfo){
        List<TSmjGoodList> tSmjGoodLists = null;
        BigDecimal amount = new BigDecimal(tOrderInfo.getMoney()/100).setScale(2);
        if(tOrderInfo.getChannel().contains("alipay")){
            if(redisUtil.get("PLATFORM_SMJSMALI"+tUserRecipientInfo.getId()+amount) == null || ((List<TSmjGoodList>)redisUtil.get("PLATFORM_SMJSMALI"+tUserRecipientInfo.getId()+amount)).size()==0){
                TSmjGoodList query = new TSmjGoodList();
                query.setRealChannelCode(tOrderInfo.getChannel());
                query.setGoodStatus(0);
                query.setUserId(tUserRecipientInfo.getUserId());
                query.setPayType("ALI");
                query.setGoodPrice(amount);
                tSmjGoodLists = itSmjGoodListService.selectTSmjGoodListListByNoAuth(query);
                logger.info("缓存中无金额对应的商品：重新获取生产缓存，{}",tSmjGoodLists.size());
                if (tSmjGoodLists.size() == 0) {
                    return null;
                }
            }else{
                logger.info("缓存中有金额对应的商品：获取第一个商品");
                tSmjGoodLists =(List<TSmjGoodList>)redisUtil.get("PLATFORM_SMJSMALI"+tUserRecipientInfo.getId()+amount+"");
            }
        }else{
            if(redisUtil.get("PLATFORM_SMJSMWX"+tUserRecipientInfo.getId()+amount) == null || ((List<TSmjGoodList>)redisUtil.get("PLATFORM_SMJSMWX"+tUserRecipientInfo.getId()+amount)).size()==0){
                TSmjGoodList query = new TSmjGoodList();
                query.setRealChannelCode(tOrderInfo.getChannel().replace("alipay","wechat"));
                query.setUserId(tUserRecipientInfo.getUserId());
                query.setGoodStatus(0);
                query.setPayType("WX");
                query.setGoodPrice(amount);
                tSmjGoodLists = itSmjGoodListService.selectTSmjGoodListListByNoAuth(query);
                logger.info("缓存中无金额对应的商品：重新获取生产缓存，{}",tSmjGoodLists.size());
                if (tSmjGoodLists.size() == 0) {
                    return null;
                }
            }else{
                logger.info("缓存中有金额对应的商品：获取第一个商品");
                tSmjGoodLists =(List<TSmjGoodList>)redisUtil.get("PLATFORM_SMJSMWX"+tUserRecipientInfo.getId()+amount+"");
            }
        }
        Collections.shuffle(tSmjGoodLists);
        logger.info("获取金额为：{}的商品前缓存的商品个数：{}",amount,tSmjGoodLists.size());
        TSmjGoodList tmpSmjGoodInfo = tSmjGoodLists.get(0);
        logger.info("获取金额为：{} 商品信息：{}",amount,JSONObject.toJSONString(tmpSmjGoodInfo));
//
//        List<WeightRandom.WeightObj<TSmjGoodList>> weightList = new ArrayList<WeightRandom.WeightObj<TSmjGoodList>>();
//        for (TSmjGoodList tSmjGoodList : tSmjGoodLists) {
//            WeightRandom.WeightObj<TSmjGoodList> a = new WeightRandom.WeightObj<TSmjGoodList>(tSmjGoodList, 1);
//            weightList.add(a);
//        }
//        WeightRandom wr = RandomUtil.weightRandom(weightList);
//        TSmjGoodList tmpSmjGoodInfo = (TSmjGoodList) wr.next();

        TSmjMachineList tSmjMachineList = itSmjMachineListService.selectTSmjMachineListById(tmpSmjGoodInfo.getMachineId());
        TOrderInfo queryPaymentOrder = new TOrderInfo();
        queryPaymentOrder.setQrcodeContent(tSmjMachineList.getMachineName());
        queryPaymentOrder.setQrcodeTxt(tmpSmjGoodInfo.getId() + "");
        queryPaymentOrder.setRecipientId(tUserRecipientInfo.getId());
        queryPaymentOrder.setStatus(1);
        queryPaymentOrder.setChannel(tOrderInfo.getChannel());
        String newdateTime = DateUtils.dealDate("10分钟前");
//        String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        queryPaymentOrder.getParams().put("beginCreateTime",newdateTime);
//        queryPaymentOrder.getParams().put("endCreateTime",dateTime);

        List<TOrderInfo> list = orderInfoService.selectTOrderInfoListByNoAuth(queryPaymentOrder);
        logger.info("查询商品是否被使用订单数量：{}",list.size());
        if(list.size()>0){
            logger.info("查询到机器：{}，货道：{}，已被订单号：{}使用，重新获取商品",tSmjMachineList.getMachineName(),tmpSmjGoodInfo.getId(),tOrderInfo.getId());

           return getPayInfoObj(tUserRecipientInfo,tOrderInfo);
        }else{
            logger.info("未被使用，直接返回");
            tSmjGoodLists.remove(0);
            tmpSmjGoodInfo.setGoodStatus(1);
            itSmjGoodListService.updateTSmjGoodList(tmpSmjGoodInfo);
            logger.info("获取金额为：{}的商品后缓存的商品个数：{}",amount,tSmjGoodLists.size());
            if(tOrderInfo.getChannel().contains("alipay")) {
                redisUtil.set("PLATFORM_SMJSMALI"+tUserRecipientInfo.getId()+amount + "", tSmjGoodLists);
            }else{
                redisUtil.set("PLATFORM_SMJSMWX"+tUserRecipientInfo.getId()+amount + "", tSmjGoodLists);
            }
            return tmpSmjGoodInfo;
        }
    }

    @Override
    public JSONObject createPayOrder(TOrderInfo orderInfo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        synchronized (this) {
            TSmjGoodList tmpSmjGoodInfo =   getPayInfoObj(userRecipientInfo,orderInfo);
            if (tmpSmjGoodInfo == null) {
                jsonObject.put("code","100");
                jsonObject.put("msg","通道异常,请稍后再试！未匹配通道收款账号");
                logger.info("========修改收款账号为不可用===============");
                return jsonObject;
            }
            TSmjMachineList tSmjMachineList = itSmjMachineListService.selectTSmjMachineListById(tmpSmjGoodInfo.getMachineId());
            String goodUrl = tmpSmjGoodInfo.getGoodUrl();
//            orderInfo.setQrcodeContent(tSmjMachineList.getMachineName());
//            orderInfo.setQrcodeTxt(tmpSmjGoodInfo.getId() + "");
//            orderInfo.setGoodsName(tmpSmjGoodInfo.getGoodHd() + "");
//            tmpSmjGoodInfo.setGoodStatus(1);
//            itSmjGoodListService.updateTSmjGoodList(tmpSmjGoodInfo);
//            orderInfoService.updateTOrderInfo(orderInfo);
//            logger.info("==========开始更新订单状态为处理中=================");
//            jsonObject.put("payUrl",goodUrl);
//            jsonObject.put("orderNo","");
//            jsonObject.put("code","200");
//            return jsonObject;

            if(orderInfo.getChannel().contains("alipay")){
                String p = getParamByUrl(goodUrl, "p");
                HashMap<String, String> dataMap = new HashMap();
                HashMap<String, String> headMap = new HashMap();
                dataMap.put("p", p);
                dataMap.put("couponCode", "");
                String[] goodUrls = goodUrl.split("payInfo_alipay");
                logger.info("请求参数：{}",JSONObject.toJSONString(dataMap));
                StringBuilder newbuf = new StringBuilder((dataMap.size() + 1) * 10);
                SignUtils.buildPayParams(newbuf, dataMap, false);
                String newStr = newbuf.toString();
                //https://vm.smshj.com/hbshengma/mobile/payInfo_alipay.html?p=490C5A18799995DBD5CF9A8614414B9F371DF2930C46054E84D7AD76AA275F2C
                //https://vm.smshj.com/hbshengma/mobile/submitpay_alipay_company.action
                String payInfo = "";
                String regionCode = "";
                if(StringUtils.isNotBlank(userRecipientInfo.getCity())){
                    regionCode = userRecipientInfo.getCity();
                }else if(StringUtils.isNotBlank(userRecipientInfo.getProvince())){
                    regionCode = userRecipientInfo.getProvince();
                }
                if(StringUtils.isNotBlank(regionCode)){
                    JSONObject proxyObj = commonService.getPoxyIp(regionCode);
                    payInfo =  HttpUtils.sendPostRequestByProxyIp(goodUrls[0] + "submitpay_alipay_company.action",newStr,headMap,proxyObj.getString("ip")+":"+proxyObj.getString("prot"));
                    orderInfo.setProxyIp(proxyObj.getString("ip")+":"+proxyObj.getString("prot"));
                }else{
                    payInfo = HttpUtils.submit(goodUrls[0] + "submitpay_alipay_company.action", dataMap);
                }

                //String payInfo = HttpUtils.submit(goodUrls[0] + "submitpay_alipay_company.action", dataMap);
                logger.info("请求返回：{}",payInfo);
                JSONObject payInfoObj = JSONObject.parseObject(payInfo);

                String payUrl = "";
                if (payInfoObj.get("code")!=null) {
                    if(payInfoObj.getString("code").equals("10000")){
                        payUrl = payInfoObj.getString("barCode");
                        orderInfo.setQrcodeContent(tSmjMachineList.getMachineName());
                        orderInfo.setQrcodeTxt(tmpSmjGoodInfo.getId() + "");
                        orderInfo.setGoodsName(tmpSmjGoodInfo.getGoodHd() + "");
                        tmpSmjGoodInfo.setGoodStatus(1);
                        itSmjGoodListService.updateTSmjGoodList(tmpSmjGoodInfo);
                        orderInfoService.updateTOrderInfo(orderInfo);
                        logger.info("==========开始更新订单状态为处理中=================");
                        jsonObject.put("payUrl",payUrl);
                        jsonObject.put("orderNo","");
                        jsonObject.put("code","200");
                        return jsonObject;
                    }else{
                        tmpSmjGoodInfo.setGoodStatus(0);
                        itSmjGoodListService.updateTSmjGoodList(tmpSmjGoodInfo);
                        jsonObject.put("code","100");
                        jsonObject.put("msg","获取连接失败"+payInfoObj.getString("msg"));
                        return jsonObject;
                    }
                } else {
                    tmpSmjGoodInfo.setGoodStatus(0);
                    itSmjGoodListService.updateTSmjGoodList(tmpSmjGoodInfo);
                    jsonObject.put("code","100");
                    jsonObject.put("msg","获取连接失败"+payInfoObj.getString("message"));
                    return jsonObject;
                }
            }else if(orderInfo.getChannel().contains("wechat")){
                orderInfo.setQrcodeContent(tSmjMachineList.getMachineName());
                orderInfo.setQrcodeTxt(tmpSmjGoodInfo.getId() + "");
                orderInfo.setGoodsName(tmpSmjGoodInfo.getGoodHd() + "");
                tmpSmjGoodInfo.setGoodStatus(1);
                itSmjGoodListService.updateTSmjGoodList(tmpSmjGoodInfo);
                orderInfoService.updateTOrderInfo(orderInfo);
                jsonObject.put("payUrl",goodUrl);
                jsonObject.put("orderNo","");
                jsonObject.put("code","200");
            }
            jsonObject.put("code","100");
            jsonObject.put("msg","获取连接失败");
            return jsonObject;

        }
    }

    @Override
    public ResponseData smartReissueOrder(TOrderInfo orderInfo) throws Exception {
        return new ResponseData();
    }
}
